package control.manager
{
	import data.MapData;
	import data.PlayerData;
	import data.TaskVO;
	
	import flash.events.NetStatusEvent;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	
	import view.layer.GameLayer;
	import view.role.MapPlayer;

	/**
	 * 本地保存数据管理器
	 * @author leo
	 * 
	 */	
	public class GSaveManager
	{
		private static var _instance :GSaveManager = null;
		
		private var sharedObj :SharedObject;
		public function GSaveManager(prv :PrivateClass)
		{
		}

		public static function get  instance():GSaveManager
		{
			if(_instance == null)
			{
				_instance = new GSaveManager(new PrivateClass());
			}
			return _instance;
		}
		/**
		 * 保存玩家数据 
		 * @param playerData
		 * 
		 */		
		public function savePlayerData(playerData :PlayerData):void
		{
			var mapData :MapData = MapManager.instance.curMapData;
			if(mapData)
			{
				playerData.curMapID = mapData.mapID;
			}
			var player :MapPlayer = RoleManager.instance.player;
			if(player && mapData)
			{
				playerData.bornPoint = MapManager.instance.getCellPoint(mapData.mapWalkGapWidth,mapData.mapWalkGapHeight,player.x,player.y);
			}
			setData(playerData,"playerData");
			trace("保存用户数据");
		}
		/**
		 * 获取玩家数据 
		 * @param name
		 * @return 
		 * 
		 */		
		public function getPlayerData(name :String = "playerData"):PlayerData
		{
			var obj :Object = getData(name);
			var playerData :PlayerData;
			if(obj)
			{
				playerData = PlayerData.changeData2PlayerData(obj);
			}
			return playerData;
		}
		
		
		/**
		 * 保存数据
		 * @param obj
		 * @param objName 
		 * @param defName
		 * 
		 */		
		private function setData(obj :Object,objName :String,defName :String= "localSharedObj"):void
		{
			this.sharedObj = SharedObject.getLocal(defName,"/");
			this.sharedObj.data[objName] = obj;
			try
			{
				this.sharedObj.flush(1000);
				this.sharedObj.addEventListener(NetStatusEvent.NET_STATUS,netHandler);
			}catch(e :Error)
			{
				
			}
		}
		/**
		 * 获取数据
		 * @param objName  单个属性值
		 * @param defName
		 * @return 
		 * 
		 */		
		private function getData(objName :String,defName :String= "localSharedObj"):Object
		{
			this.sharedObj = SharedObject.getLocal(defName,"/");
			if(this.sharedObj.data[objName] != null)
			{
				return this.sharedObj.data[objName];
			}
			
			return null;
		}
		
		
		private function netHandler(e :NetStatusEvent):void
		{
			switch(e.info.code)
			{
				case "SharedObject.Flush.Failed":
					trace("存储失败");
					break;
				case "SharedObject.Flush.Success":
					trace("存储成功");
					break;
			}
			this.sharedObj.removeEventListener(NetStatusEvent.NET_STATUS,netHandler);
		}
		
	}
}

class PrivateClass{}